import { css } from "@emotion/react";
import { completeAllImgUrl, getImgListFormRichText } from "common/utils/utils";
import { Fragment, useEffect, useMemo, useRef, useState } from "react";
import {Image} from 'antd';
import { useMemoizedFn } from "ahooks";

const trimQuery = (str: string)=>{
  return str.replace(/\?.*?$/, '')
}
export default function RichText({content}:{content: string}){
  const containerRef = useRef<HTMLDivElement>(null);

  const [imagePreview, setImagePreview] = useState<{
    visible: boolean;
    current: number;
  }>({
    visible: false,
    current: 0,
  });

  const finalHtml = useMemo(()=>{
    return completeAllImgUrl(content, false, '?x-oss-process=image/resize,w_1322')
  }, [content])

  const imgList = useMemo(()=>{
    return getImgListFormRichText(finalHtml).map(trimQuery);
  },[finalHtml])

  const onClick = useMemoizedFn((e: MouseEvent)=>{
    if(e.target?.nodeName?.toLocaleLowerCase() === 'img'){
      setImagePreview({
        visible: true,
        current: imgList.findIndex(item=>e.target?.src && item === trimQuery(e.target.src)),
      });
    }
  })

  useEffect(() => {
    containerRef.current?.addEventListener('click',onClick);
    return ()=>{
      containerRef.current?.removeEventListener('click',onClick);
    }
  }, []);

  return <Fragment>
    <div ref={containerRef} css={css`
            img{
              max-width: 100%;
              cursor: pointer;
            }
          
          `} dangerouslySetInnerHTML={{
      __html: finalHtml,
    }} />
    <Image.PreviewGroup
      preview={{
        visible: imagePreview.visible,
        onVisibleChange:(val)=>{
          setImagePreview({
            visible: val,
            current: 0,
          })
        },
        current: imagePreview.current,
        onChange: (val)=> {
          setImagePreview(origin=>{
            return {
              ...origin,
              current: val,
            }
          })
        }
      }}
      items={imgList}
    >
    </Image.PreviewGroup>
  </Fragment>
}
